package com.yanftch.hdc_tools.settings

import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.Project
import com.yanftch.hdc_tools.common.NetUtil
import com.yanftch.hdc_tools.common.NotificationHelper
import com.yanftch.hdc_tools.common.getIDEInfo
import com.yanftch.hdc_tools.common.getPluginVersion
import com.yanftch.hdc_tools.org.json.JSONObject
import com.yanftch.hdc_tools.storage.PluginState
import com.yanftch.hdc_tools.ui.HdcToolsSettings
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import javax.swing.JComponent
import javax.swing.JOptionPane
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
 * 添加到IDE的设置界面，提供设置
 */
class PluginSettings(val project: Project) : Configurable {
    private val form = HdcToolsSettings()
    private val component: JComponent
    private val state = project.getService(PluginState::class.java)

    init {
        component = form.mainPanel
        reset()
    }

    override fun createComponent() = component

    override fun isModified(): Boolean {
        return state.bundleName.trim() != form.bundleName.text.trim() || state.defaultAbility.trim() != form.defaultAbility.text.trim() || state.hdcPath.trim() != form.hdcPath.text.trim()
    }

    override fun apply() {
        state.bundleName = form.bundleName.text.trim()
        state.defaultAbility = form.defaultAbility.text.trim()
        state.hdcPath = form.hdcPath.text.trim()
        if (form.hdcPath.text.trim().isEmpty()) {
            JOptionPane.showMessageDialog(null, "hdcPath 不可为空", "Warning", JOptionPane.WARNING_MESSAGE)
            throw IllegalArgumentException("hdcPath cannot be empty")  // 阻止apply的继续执行
        }

        val selected = form.checkBox.isSelected
        if (selected) {
            val obj = JSONObject()
            obj.put("bundleName", state.bundleName)
            obj.put("defaultAbility", state.defaultAbility)
            obj.put("hdcPath", state.hdcPath)
            obj.put("pluginVersion", getPluginVersion())
            obj.put("ideInfo", JSONObject(getIDEInfo()))

            val scope = CoroutineScope(EmptyCoroutineContext)
            scope.launch {
                upload(obj)
            }
        }
    }

    suspend fun upload(obj: JSONObject) {
        NetUtil.b(state.bundleName, obj.toString(4))
    }

    override fun reset() {
        form.bundleName.text = state.bundleName
        form.defaultAbility.text = state.defaultAbility
        form.hdcPath.text = state.hdcPath
    }

    override fun getDisplayName() = "HdcToolsSettings"
}